package io.github.mymonstercat.utils;

import io.github.mymonstercat.entity.Body;
import io.github.mymonstercat.service.impl.FileWarningServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class FileTransformer {

    @Resource
    private FileWarningServiceImpl fileWarningService;

    @Value("${pdf.chineseCharacterThreshold}")
    private int chineseCharacterThreshold;

    public List<Body> PDFToImageDivision(String fileName, String pdfFilePath, String outputFolder) {
        List<Body> result = new ArrayList<>();
        // 创建输出文件夹（如果不存在）
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        int i = 1;
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            int pageNum = 1;

            for (PDPage page : document.getPages()) {
                PDResources resources = page.getResources();
                if (resources != null) {
                    int imageIndex = 1;
                    String imageFileName = "";
                    for (COSName key : resources.getXObjectNames()) {
                        if (resources.isImageXObject(key)) {
                            PDImageXObject image = (PDImageXObject) resources.getXObject(key);
                            BufferedImage bufferedImage = image.getImage();
                            if (bufferedImage != null) {
                                imageFileName = outputFolder  + "page_" + pageNum + "_img_" + imageIndex + ".png";
                                File outputFile = new File(imageFileName);
                                ImageIO.write(bufferedImage, "png", outputFile);
                                if (StringUtils.isNotBlank(imageFileName)) {
                                    Body rate = fileWarningService.getRate(imageFileName,  "page_" + pageNum + "_img_" + imageIndex + ".png");
                                    if (rate != null) {
                                        rate.setNum(String.valueOf(i));
                                        result.add(rate);
                                        i++;
                                    }
                                }
                                imageIndex++;
                            }
                        }
                    }
                }
                pageNum++;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return result;
    }

    public boolean hasPageWithMoreThan30ChineseChars(String pdfPath) throws IOException {
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            PDFTextStripper stripper = new PDFTextStripper();
            int numberOfPages = document.getNumberOfPages();

            // 正则表达式用于匹配汉字字符
            Pattern chineseCharPattern = Pattern.compile("[\\u4e00-\\u9fa5]");

            for (int k = 1; k <= numberOfPages; k++) {
                stripper.setStartPage(k);
                stripper.setEndPage(k);
                String text = stripper.getText(document);

                // 统计汉字字符数
                Matcher matcher = chineseCharPattern.matcher(text);
                int chineseCharCount = 0;
                while (matcher.find()) {
                    chineseCharCount++;
                    if (chineseCharCount > chineseCharacterThreshold) {
                        return true; // 该页汉字字符数超过30
                    }
                }
            }
        }
        return false; // 所有页汉字字符数都不超过30
    }

    public List<Body> convertPagesWithMoreThan30ChineseCharsToImages(String pdfPath, String outputDir) throws IOException {
        List<Body> result = new ArrayList<>();
        // 创建输出文件夹（如果不存在）
        File folder = new File(outputDir);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        int k = 1;
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            PDFTextStripper stripper = new PDFTextStripper();
            int numberOfPages = document.getNumberOfPages();

            // 正则表达式用于匹配汉字字符
            Pattern chineseCharPattern = Pattern.compile("[\\u4e00-\\u9fa5]");

            for (int i = 1; i <= numberOfPages; i++) {
                stripper.setStartPage(i);
                stripper.setEndPage(i);
                String text = stripper.getText(document);

                // 统计汉字字符数
                Matcher matcher = chineseCharPattern.matcher(text);
                int chineseCharCount = 0;
                while (matcher.find()) {
                    chineseCharCount++;
                }

                // 如果该页的汉字字符数超过30，将其转换为图像
                if (chineseCharCount > chineseCharacterThreshold) {
                    BufferedImage image = pdfRenderer.renderImageWithDPI(i - 1, 300, ImageType.RGB);
                    String imageName = outputDir + "page_" + i + ".png";
                    ImageIO.write(image, "PNG", new File(imageName));
                    Body rate = fileWarningService.getRate(imageName, "page_" + k + ".png");
                    if (rate != null) {
                        rate.setNum(String.valueOf(k));
                        result.add(rate);
                        k++;
                        System.out.println("Page " + i + " converted to image: " + imageName);
                    }
                }
            }
        }
        return result;
    }
}
